package com.jiot.validator;

import com.jfinal.core.Controller;
import com.jfinal.validate.Validator;

/**
 * 
 * @author 张烨
 * @description 基础校验器
 * @time 2016年10月28日
 */
public abstract class BaseValidator extends Validator {

	//普通字符串长度限制
	public static final String STRING_SIZE = "^.{0,20}$";
	//6-20未用户名
	public static final String USER_NAME = "^[A-Za-z0-9]{6,20}$";
	//密码必须是数字和字母
	public static final String USER_PASSWORD = "^(?![a-zA-z]+$)(?!\\d+$)(?![!@#$%^&*]+$)[a-zA-Z\\d!@#$%^&*-]{6,32}$";
	//手机号
	public static final String PHONE = "^1[3456789]\\d{9}$";
	//身份证校验，初级校验，具体规则有一套算法
	public static final String ID_CARD = "^\\d{15}$|^\\d{17}([0-9]|X)$";
	//邮箱
	protected static final String emailAddressPatternOrPhone = 
			"(\\b(^['_A-Za-z0-9-]+(\\.['_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$)\\b)|(^\\\\d{15}$|^\\\\d{17}([0-9]|X)$)";
	
	
	

	{this.setShortCircuit(true);}

	/**
	 * 输入6-20位的字母或数字
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validateAccount(String field,String errorKey,String errorMsg){
		validateRegex(field, USER_NAME, false, errorKey, errorMsg);
	}

	/**
	 * 0-20字符长度
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validateStringSize(String field,String errorKey,String errorMsg){
		validateRegex(field, STRING_SIZE, false, errorKey, errorMsg);
	}
	
	/**
	 * 验证手机号格式
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validatePhone(String field,String errorKey,String errorMsg){
		validateRegex(field, PHONE, false, errorKey, errorMsg);
	}
	/**
	 * 账号号格式
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validatePhoneOrPhon(String field,String errorKey,String errorMsg){
		validateRegex(field, emailAddressPatternOrPhone, false, errorKey, errorMsg);
	}
	
	/**
	 * 验证身份证号码
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validateIdCard(String field,String errorKey,String errorMsg){
		validateRegex(field, ID_CARD, false, errorKey, errorMsg);
	}

	/**
	 * 密码必须是数字和字母
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validatePassword(String field,String errorKey,String errorMsg){
		validateRegex(field, USER_PASSWORD, false, errorKey, errorMsg);
	}

	
	protected void validateSize(String field,String errorKey,String errorMsg){
		validateRegex(field, PHONE, false, errorKey, errorMsg);
	}

	@Override
	protected void handleError(Controller c) {
		c.setAttr("result", false);
		c.renderJson(new String[] { "result", "msg" });
	}
}
